package com.gxa.community.admin.jms;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxa.community.admin.mapper.MessageIdMapper;
import com.gxa.community.admin.mapper.goods.GoodsInfoMapper;
import com.gxa.community.core.pojo.domain.MessageId;
import com.gxa.community.core.pojo.domain.goodsdo.GoodsInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;


import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class GoodsStockListener {
    @Autowired
    private MessageIdMapper messageIdMapper;
    @Autowired
    private GoodsInfoMapper goodsInfoMapper;

    @JmsListener(destination = "reduceGoodsStock",containerFactory = "containerFactory")
    public synchronized void reduceGoodsStock(Message message, Session session) throws JMSException {
        //利用messageID防止重复消费
        String jmsMessageID = message.getJMSMessageID();
        //去数据库中查询是否有
        MessageId messageId = messageIdMapper.selectOne(new LambdaQueryWrapper<MessageId>().eq(MessageId::getMsgId, jmsMessageID));
        if (messageId!=null){
            message.acknowledge();
            return;
        }
        ActiveMQObjectMessage activeMQObjectMessage = (ActiveMQObjectMessage) message;
        Serializable object = activeMQObjectMessage.getObject();
        Map<Integer,Integer> map = (Map<Integer, Integer>) object;
        Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
        for (Map.Entry<Integer, Integer> entry : entries) {
            Integer goodsId = entry.getKey();
            Integer goodsNum = entry.getValue();
            //先获取该商品原库存
            GoodsInfo goodsInfo = goodsInfoMapper.selectById(goodsId);
            Integer oldNum = goodsInfo.getNum();
            goodsInfo.setNum(oldNum-goodsNum);
            goodsInfoMapper.updateById(goodsInfo);
        }
        messageId.setMsgId(jmsMessageID);
        messageId.setStatus(1);
        messageId.setTime(System.currentTimeMillis());
        messageIdMapper.insert(messageId);
    }
}
